# -*- coding: utf-8 -*-

from flask import request, jsonify
from face_recognition import app, model_manager, LoggerUtil
from face_recognition.models.user_info import user_schema
from face_recognition.recognition.image_tools import ImageTools
from face_recognition.service.user_info_service import UserInfoService
from face_recognition.views.wrapers import wraper_need_login


@app.route('/face_recognition/detect', methods=['POST'])
def detect():
	"""
	根据传入的图片base64编码来获取图片中的人脸特征并且识别图片中的用户
	:return:
	"""
	if request.method == 'POST':
		data = request.get_json()
		if "image_base64" in data.keys() and len(data["image_base64"]) > 0:
			image_tools = ImageTools()
			user_info_service = UserInfoService()
			feature = image_tools.get_feature_from_base64(data["image_base64"])
			if feature is not None:
				min_confidence = app.config.get("MIN_CONFIDENCE")
				rst, confidence = model_manager.recognizer.predict(feature)
				LoggerUtil.debug("rst=" + str(rst) + ",  confidence=" + str(confidence))
				if confidence > min_confidence:
					user = user_info_service.get_with_index_number(rst)
					result = {"status": "success", "confidence": round(confidence, 2),
					          "user": user_schema.dump(user).data, "message": "人脸识别完成！"}
				else:
					LoggerUtil.debug("人脸识别完成，但置信度太低（小于" + str(min_confidence) + "）, confidence=" + str(confidence))
					result = {"status": "error", "message": "人脸识别完成，但置信度太低（小于" + str(min_confidence) + "），不使用此结果！"}
			else:
				result = {"status": "error", "message": "未获取到人脸信息！"}
		else:
			result = {"status": "error", "message": "未获取到需要识别的人脸图片！"}
		return jsonify(result)
